package com.util.webpage;

import org.apache.commons.lang.math.NumberUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class PageData extends HashMap implements Map {

    private static final long serialVersionUID = 1L;

    HttpServletRequest request;

    public PageData() {
        super();
    }

    ;

    public PageData(HttpServletRequest request) {
        this.request = request;
        Map properties = request.getParameterMap();
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();

            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            this.put(name, value);
        }
    }

    public String getString(Object key) {
        return (String) get(key);
    }

    public Date getDate(Object key) {
        return (Date) get(key);
    }

    public int getInteger(Object key) {
        Object valueObj = get(key);
        if (valueObj instanceof String) {
            return NumberUtils.toInt((String) valueObj, 0);
        }
        return (Integer) valueObj;
    }

    public BigDecimal getDecimal(Object key) {
        Object valueObj = get(key);
        if (valueObj instanceof String) {
            return NumberUtils.createBigDecimal((String) valueObj);
        }
        return (BigDecimal) valueObj;
    }

    public Double getDouble(Object key) {
        Object valueObj = get(key);
        if (valueObj instanceof String) {
            return NumberUtils.toDouble((String) valueObj, 0);
        }
        return (Double) valueObj;
    }

}
